package com.sk.weichat.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.GroupFragmentAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.RoomMember;
import com.sk.weichat.bean.message.MucRoom;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.OnCompleteListener;
import com.sk.weichat.db.dao.RoomMemberDao;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.EasyFragment;
import com.sk.weichat.ui.groupchat.TabSelectContactsActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.ui.message.TabFriendActivity;
import com.sk.weichat.ui.message.multi.EventGroupStatus;
import com.sk.weichat.ui.message.search.NetSearchRoomsActivity;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import okhttp3.Call;

/**
 * 群组列表
 * create by swy 2019-07-15
 */
public class TabGroupFragment extends EasyFragment {

    private SmartRefreshLayout refreshLayout;
    private RelativeLayout layout_tab_friend_search;

    private LinearLayout ll_open_group;
    private ImageView img_open_group;
    private RecyclerView recy_open_group;


    private LinearLayout ll_common_group;
    private ImageView img_common_group;
    private RecyclerView recy_comment_group;

    private GroupFragmentAdapter mOpenAdapter;
    private List<BaseSortModel<Friend>> mOpenSortFriends;

    private GroupFragmentAdapter mCommentAdapter;
    private List<BaseSortModel<Friend>> mCommentSortFriends;
    private String mLoginUserId;

    private View linearGroupEmpty;
    private TextView tv_create_group;

    public TabGroupFragment() {
        mOpenSortFriends = new ArrayList<>();
        mCommentSortFriends = new ArrayList<>();
    }

    @Override
    protected int inflateLayoutId() {
        return R.layout.fragment_tab_group;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        mLoginUserId = coreManager.getSelf().getUserId();
        initView();
        updateRoom();
        EventBus.getDefault().register(this);
    }

    private void initView() {
        refreshLayout = findViewById(R.id.refresh_layout);
        refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                updateRoom();
            }
        });

        layout_tab_friend_search = findViewById(R.id.layout_tab_friend_search);
        linearGroupEmpty = findViewById(R.id.linear_empty_tips);
        tv_create_group = findViewById(R.id.tv_create_group);
        tv_create_group.setOnClickListener(this);
        layout_tab_friend_search.setOnClickListener(this);


        /*公开群聊*/
        ll_open_group = findViewById(R.id.ll_open_group);
        img_open_group = findViewById(R.id.img_open_group);
        recy_open_group = findViewById(R.id.recy_open_group);
        recy_open_group.setLayoutManager(new LinearLayoutManager(mActivity));
        ll_open_group.setOnClickListener(this);

        /*普通群聊*/
        ll_common_group = findViewById(R.id.ll_common_group);
        img_common_group = findViewById(R.id.img_common_group);
        recy_comment_group = findViewById(R.id.recy_comment_group);
        recy_comment_group.setLayoutManager(new LinearLayoutManager(mActivity));
        ll_common_group.setOnClickListener(this);

        initListAdapter();
    }

    //初始化适配器及事件
    private void initListAdapter() {
        mOpenAdapter = new GroupFragmentAdapter(mOpenSortFriends);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_open_group.getItemAnimator()).setSupportsChangeAnimations(false);
        mOpenAdapter.setHasStableIds(true);
        recy_open_group.setAdapter(mOpenAdapter);
        mOpenAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mOpenSortFriends.get(position).getBean();
                Intent intent = new Intent(getActivity(), MucChatActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                intent.putExtra(AppConstant.EXTRA_NICK_NAME, friend.getNickName());
                intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                startActivity(intent);
                if (friend.getUnReadNum() > 0) {// 如该群组未读消息数量大于1, 刷新MessageFragment
                    MsgBroadcast.broadcastMsgNumReset(getActivity());
                    MsgBroadcast.broadcastMsgUiUpdate(getActivity());
                }
            }
        });

        mCommentAdapter = new GroupFragmentAdapter(mCommentSortFriends);
        mCommentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mCommentSortFriends.get(position).getBean();
                Intent intent = new Intent(getActivity(), MucChatActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                intent.putExtra(AppConstant.EXTRA_NICK_NAME, friend.getNickName());
                intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                startActivity(intent);
                if (friend.getUnReadNum() > 0) {// 如该群组未读消息数量大于1, 刷新MessageFragment
                    MsgBroadcast.broadcastMsgNumReset(getActivity());
                    MsgBroadcast.broadcastMsgUiUpdate(getActivity());
                }
            }
        });

        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_comment_group.getItemAnimator()).setSupportsChangeAnimations(false);
        mCommentAdapter.setHasStableIds(true);
        recy_comment_group.setAdapter(mCommentAdapter);
    }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(EventGroupStatus eventGroupStatus) {
        if (eventGroupStatus.getWhichStatus() == 10002) {// 转让群
            updateRoom();
            ((TabFriendActivity)getActivity()).downloadUserInfo();
        }else if (eventGroupStatus.getWhichStatus() == 111111){//修改群名称
            updateRoom();
            ((TabFriendActivity)getActivity()).downloadUserInfo();
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_tab_friend_search:
                startActivity(new Intent(mActivity, NetSearchRoomsActivity.class).putExtra("search_user", ""));
                break;
            case R.id.tv_create_group:
                startActivity(new Intent(getActivity(), TabSelectContactsActivity.class));
                break;
            case R.id.ll_open_group:
                if (recy_open_group.getVisibility()==View.VISIBLE){
                    img_open_group.setBackgroundResource(R.mipmap.icon_group_arrow_close);
                    recy_open_group.setVisibility(View.GONE);
                }else {
                    img_open_group.setBackgroundResource(R.mipmap.icon_group_arrow_open);
                    recy_open_group.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.ll_common_group:
                if (recy_comment_group.getVisibility()==View.VISIBLE){
                    img_common_group.setBackgroundResource(R.mipmap.icon_group_arrow_close);
                    recy_comment_group.setVisibility(View.GONE);
                }else {
                    img_common_group.setBackgroundResource(R.mipmap.icon_group_arrow_open);
                    recy_comment_group.setVisibility(View.VISIBLE);
                }
                break;

        }
    }


    //加载群成员（用于显示群头像）
    private void loadMembers(final String roomId) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", roomId);
        params.put("pageSize", Constants.MUC_MEMBER_PAGE_SIZE);
        HttpUtils.get().url(coreManager.getConfig().ROOM_GET)
                .params(params)
                .build()
                .execute(new BaseCallback<MucRoom>(MucRoom.class) {

                             @Override
                             public void onResponse(ObjectResult<MucRoom> result) {
                                 if (result.getResultCode() == 1 && result.getData() != null) {
                                     final MucRoom mucRoom = result.getData();
                                     update(mucRoom);
                                 } else {
                                     ToastUtil.showErrorData(getContext());
                                 }
                             }

                             @Override
                             public void onError(Call call, Exception e) {
                                 ToastUtil.showNetError(getContext());
                             }
                         }
                );
    }

    private void update(MucRoom mucRoom) {
        // 更新部分群属性
        MyApplication.getInstance().saveGroupPartStatus(mucRoom.getJid(), mucRoom.getShowRead(), mucRoom.getAllowSendCard(),
                mucRoom.getAllowConference(), mucRoom.getAllowSpeakCourse(), mucRoom.getTalkTime());
        PreferenceUtils.putBoolean(MyApplication.getContext(),
                Constants.IS_NEED_OWNER_ALLOW_NORMAL_INVITE_FRIEND + mucRoom.getJid(), mucRoom.getIsNeedVerify() == 1);
        PreferenceUtils.putBoolean(MyApplication.getContext(),
                Constants.IS_ALLOW_NORMAL_SEND_UPLOAD + mucRoom.getJid(), mucRoom.getAllowUploadFile() == 1);
        List<RoomMember> roomMemberList = new ArrayList<>();
        for (int i = 0; i < mucRoom.getMembers().size(); i++) {
            RoomMember roomMember = new RoomMember();
            roomMember.setRoomId(mucRoom.getId());
            roomMember.setUserId(mucRoom.getMembers().get(i).getUserId());
            roomMember.setUserName(mucRoom.getMembers().get(i).getNickName());
            if (TextUtils.isEmpty(mucRoom.getMembers().get(i).getRemarkName())) {
                roomMember.setCardName(mucRoom.getMembers().get(i).getNickName());
            } else {
                roomMember.setCardName(mucRoom.getMembers().get(i).getRemarkName());
            }
            roomMember.setRole(mucRoom.getMembers().get(i).getRole());
            roomMember.setCreateTime(mucRoom.getMembers().get(i).getCreateTime());
            roomMemberList.add(roomMember);
        }
        AsyncUtils.doAsync(this, mucChatActivityAsyncContext -> {
            for (int i = 0; i < roomMemberList.size(); i++) {// 在异步任务内存储
                RoomMemberDao.getInstance().saveSingleRoomMember(mucRoom.getId(), roomMemberList.get(i));
            }
        });
    }

    /**
     * 下载我的群组
     */
    private void updateRoom() {
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("type", "0");
        params.put("pageIndex", "0");
        params.put("pageSize", "1000");// 给一个尽量大的值

        HttpUtils.get().url(coreManager.getConfig().ROOM_LIST_HIS)
                .params(params)
                .build()
                .execute(new ListCallback<MucRoom>(MucRoom.class) {
                    @Override
                    public void onResponse(ArrayResult<MucRoom> result) {
                        if (result.getResultCode() == 1) {
                            for (int i = 0; i < result.getData().size(); i++) {
                                RoomMemberDao.getInstance().updateRoomMemberRole(result.getData().get(i).getId(),mLoginUserId,result.getData().get(i).getMember().getRole());
                            }
                            FriendDao.getInstance().addRooms(mHandler, mLoginUserId, result.getData(),
                                    new OnCompleteListener() {
                                        @Override
                                        public void onCompleted() {// 下载完成
                                            if (coreManager.isLogin()) {
                                                // 1.调用smack内join方法加入群组
                                                List<Friend> mFriends = FriendDao.getInstance().getAllRooms(mLoginUserId);
                                                for (int i = 0; i < mFriends.size(); i++) {// 已加入的群组不会重复加入，方法内已去重
                                                    coreManager.joinMucChat(mFriends.get(i).getUserId(), 0);
                                                }
                                                // 2.更新我的群组列表
                                                Map<String, Integer> existMap = new HashMap<>();
                                                List<BaseSortModel<Friend>> sortedList = SortHelper.toSortedModelList(mFriends, existMap, Friend::getShowName);

                                                if (sortedList != null && sortedList.size() > 0) {
                                                    linearGroupEmpty.setVisibility(View.GONE);
                                                } else {
                                                    linearGroupEmpty.setVisibility(View.VISIBLE);
                                                }
                                                mOpenSortFriends.clear();
                                                mCommentSortFriends.clear();
                                                for (int i = 0; i <sortedList.size() ; i++) {
                                                    if (sortedList.get(i).getBean().getIsLook()==0){
                                                        mOpenSortFriends.add(sortedList.get(i));
                                                    }else {
                                                        mCommentSortFriends.add(sortedList.get(i));
                                                    }
                                                }
                                                mOpenAdapter.notifyDataSetChanged();
                                                mCommentAdapter.notifyDataSetChanged();

                                                if (mOpenSortFriends.size()==0){
                                                    ll_open_group.setVisibility(View.GONE);
                                                    recy_open_group.setVisibility(View.GONE);
                                                }else {
                                                    ll_open_group.setVisibility(View.VISIBLE);
                                                    recy_open_group.setVisibility(View.VISIBLE);

                                                }
                                                if (mCommentSortFriends.size()==0){
                                                    ll_common_group.setVisibility(View.GONE);
                                                    recy_comment_group.setVisibility(View.GONE);
                                                }else {
                                                    ll_common_group.setVisibility(View.VISIBLE);
                                                    recy_comment_group.setVisibility(View.VISIBLE);

                                                }
                                                refreshLayout.finishRefresh();
                                                for (int i = 0; i < mCommentSortFriends.size(); i++) {
                                                    loadMembers(mCommentSortFriends.get(i).getBean().getRoomId());
                                                }
                                            }
                                        }
                                    });
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        refreshLayout.finishRefresh();
                        ToastUtil.showNetError(getActivity());
                    }
                });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 这个没注册时取消注册也不会崩溃，
        EventBus.getDefault().unregister(this);
    }
}
